<template>
  <div class="card">
    <!-- 始终可见的部分 -->
    <div class="card-header">
      <h2>卡片标题</h2>
      <button @click="toggleDetails">{{ isExpanded ? '收起' : '展开' }} 详细信息</button>
    </div>

    <!-- 可切换的部分 -->
    <transition
      @before-enter="beforeEnter"
      @enter="enter"
      @after-enter="afterEnter"
      @before-leave="beforeLeave"
      @leave="leave"
      @after-leave="afterLeave"
    >
      <div class="card-details" ref="details">
        <p >
          这里是详细信息内容。你可以在这里添加任何你想展示的内容，例如文本、图片、列表等。
        </p>
        <p v-if="isExpanded" >
          更多详细内容可以在这里添加，以测试高度变化时的过渡效果。
        </p>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "ExpandableCard",
  data() {
    return {
      isExpanded: false
    };
  },
  methods: {
    toggleDetails() {
      this.isExpanded = !this.isExpanded;
    },
    // 过渡钩子
    beforeEnter(el) {
      el.style.height = '0';
      el.style.opacity = '0';
    },
    enter(el) {
      const height = el.scrollHeight;
      el.style.transition = 'height 0.5s ease, opacity 0.5s ease';
      el.style.height = height + 'px';
      el.style.opacity = '1';
    },
    afterEnter(el) {
      el.style.height = 'auto';
      el.style.opacity = '1';
      el.style.transition = '';
    },
    beforeLeave(el) {
      el.style.height = el.scrollHeight + 'px';
      el.style.opacity = '1';
      el.style.transition = 'height 0.5s ease, opacity 0.5s ease';
    },
    leave(el) {
      el.style.height = '0';
      el.style.opacity = '0';
    },
    afterLeave(el) {
      el.style.height = '';
      el.style.opacity = '';
      el.style.transition = '';
    }
  }
};
</script>

<style scoped>
.card {
  width: 400px;
  margin: 20px auto;
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f5f5;
}

.card-header h2 {
  margin: 0;
  font-size: 1.2em;
}

.card-header button {
  padding: 6px 12px;
  cursor: pointer;
  border: none;
  background-color: #3498db;
  color: #fff;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.card-header button:hover {
  background-color: #2980b9;
}

.card-details {
  padding: 15px 20px;
  background-color: #fff;
  border-top: 1px solid #ddd;
}

.card-details p {
  margin: 10px 0;
  line-height: 1.5;
}
</style>
